#python 3.8
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

# from pkg.notice.notice_base import NoticeBaseNoticeBase

class DingNotice():
    """
    钉钉通知
    """
    def __init__(self, url, secret):
        self.url = url
        self.secret = secret
    
    # 发送消息
    def send(self, msg):
        timestamp, sign = self.sign()
        url = self.url + '&timestamp=' + timestamp + '&sign=' + sign
        headers = {
            'Content-Type': 'application/json'
        }
        data = {
            "msgtype": "text",
            "text": {
                "content": msg
            }
        }
        response = requests.post(url, headers=headers, json=data)
    
    # 加签
    def sign(self):
        timestamp = str(round(time.time() * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        print(timestamp)
        print(sign)
        return timestamp, sign
    
if __name__ == '__main__':
    url = "https://oapi.dingtalk.com/robot/send?access_token=967e7153afc8423c52f3400a4f234e2c0ac2623a526fe72d034f089b7468add5"
    secret = "SECe795b5c61f48a7da9d0e4c7bfc0f9a5f0040df106d4e4d2f3c6952745447376e"
    ding = DingNotice(url, secret)
    ding.send("hello world")
